package org.dub.provider.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.config.annotation.DubboService;
import org.dub.api.service.UserStreamService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created By bobin on 2024/7/28
 */
@DubboService
@Slf4j
public class UserStreamServiceImpl implements UserStreamService {

    @Override
    public StreamObserver<String> sayHello(StreamObserver<String> replyObserver) {
        return new StreamObserver<>() {

            private List<String> requestlist = new ArrayList<>();
            //双端流式调用
            @Override
            public void onNext(String request) {
                log.info("receive data: {}", request);
                requestlist.add(request);
                // 发送给响应
                replyObserver.onNext(request);
                //replyObserver.onCompleted();
            }

            @Override
            public void onError(Throwable throwable) {
                log.error("error", throwable);
                // 发送响应
                replyObserver.onError(throwable);
            }

            @Override
            public void onCompleted() {
                log.info("client send completed");
                for (String request : requestlist) {
                    log.info("---received data: {}", request);
                }
                replyObserver.onCompleted();
            }
        };
    }
}
